import React, { useEffect, useState ,useRef } from 'react';
import styles from './index.module.scss';
import {
  Form,
  Button,
  Card,
  Breadcrumb,
  Radio,
  Select,
  DatePicker,
  Space,
  Table,
  Image,
  Tag,
  Modal,
  message
} from 'antd';
// import 'moment/locale/zh-cn';
// import locale from 'antd/es/date-picker/locale/zh_CN';
import { Link } from 'react-router-dom';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';

import { getChannels, getArticles ,delArticle} from '@/store/actions';
import { useDispatch, useSelector } from 'react-redux';

// 通过 colums 配置渲染列表
import defaultImg from "@/assets/error.png";
import { useHistory } from 'react-router-dom/cjs/react-router-dom.min';



import  Channel from '@/components/Channel'

// 阅读状态数据（不同状态文字和颜色不一样）
const statusLabel = [
  { text: "草稿", color: "default" },
  { text: "待审核", color: "blue" },
  { text: "审核通过", color: "green" },
  { text: "审核拒绝", color: "red" },
];







export default function Article() {
  const dispatch = useDispatch();
  const  history= useHistory()
// 请求参数
const params = useRef({
  page: 1,
  per_page: 20,
  channel_id: undefined,
  status: undefined,
  begin_pubdate: undefined,
  end_pubdate: undefined,
});



const columns = [
  {
    title: '封面',
    dataIndex: 'cover',
    key: 'cover',
    render: (cover) => (<Image
      src={cover?.images?.[0] || defaultImg}
      style={{ objectFit: "cover" }}
      width={200}
      height={120}
    />)  ,
  },
  {
    title: '标题',
    dataIndex: 'title',
    key: 'title',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    render: (status) => {
       const info= statusLabel[status];
       return <Tag color={info.color}>{info.text}</Tag>;
    }  ,
  },
  {
    title: '发布时间',
    dataIndex: 'pubdate',
    key: 'pubdate',
  },
  {
    title: '阅读数',
    dataIndex: 'read_count',
    key: 'read_count',
  },
  {
    title: '评论数',
    dataIndex: 'comment_count',
    key: 'comment_count',
  },
  {
    title: '点赞数',
    dataIndex: 'like_count',
    key: 'like_count',
  },
  {
    title: '操作',
    key: 'action',
    render: (record) => (
      <Space size="middle">
        <Button type="link" icon={<EditOutlined />} 
        onClick={()=>editArticleFn(record.id)}
        />
        <Button type="link" icon={<DeleteOutlined />} 
        onClick={()=>delArticleFn(record.id)}
        />
      </Space>
    ),
  },
];




  useEffect(() => {
    // 获取频道数据
    dispatch(getChannels());
    // 获取文章数据
    // dispatch(getArticles());

    dispatch(getArticles(params.current));
  }, [dispatch]);


  //拿到列表渲染数据
  const { channels, results, page, per_page, total_count } = useSelector(
    (state) => state.article
  );

  console.log('results', results);




// 改变筛选条件查询
// const  onFinish=(values)=>{
//   // console.log(values)
// const  params={}
// params.status= values.status
// params.channel_id = values.channel_id;
//  if(values.dateArr) {
//   params.begin_pubdate= values.dateArr[0].format('YYYY-MM-DD HH:mm:ss')
//   params.end_pubdate = values.dateArr[1].format(  "YYYY-MM-DD HH:mm:ss");
//  }else  {
//   params.begin_pubdate = undefined;
//   params.end_pubdate = undefined;
//  }

//  dispatch(getArticles(params))

// }
const onFinish = (values) => {
  params.current.status = values.status;
  params.current.channel_id = values.channel_id;
  console.log(values);
  if (values.dateArr) {
    params.current.begin_pubdate = values.dateArr[0].format(
      "YYYY-MM-DD HH:mm:ss"
    );
    params.current.end_pubdate = values.dateArr[1].format(
      "YYYY-MM-DD HH:mm:ss"
    );
  } else {
    params.current.begin_pubdate = undefined;
    params.current.end_pubdate = undefined;
  }
  params.current.page = 1
  dispatch(getArticles(params.current));
};



// 实现分页功能，支持分页页码和分页条数设置
// 进行分页查询的时候，筛选条件的参数需要保留。
const  onPageChange=(page,pageSize)=>{
  // const params={}
  // params.page=page
  // params.pageSize=pageSize
  // dispatch(getArticles(params))
  params.current.page = page
  params.current.per_page = pageSize
  dispatch(getArticles(params.current));

}

//  删除 文章 
const  delArticleFn=(id)=>{
  Modal.confirm({
    title: '您是否确认删除该文章？',
    cancelText: '取消',
    okText: '确认',
    onOk: async ()=>{
       await  dispatch(delArticle(id))
       await dispatch(getArticles(params.current));
       message.success('删除成功')
    }
  })
}
//编辑
const  editArticleFn=(id)=>{
  history.push(`/home/publish/${id}`)

}



  return (
    <div className={styles.root}>
      <Card
        title={
          // 面包屑
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>内容管理</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        {/* 表单 */}
        <Form  onFinish={onFinish}>
          <Form.Item label="状态："  name='status'>
          <Radio.Group>
            <Radio value={undefined}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>已通过</Radio>
              <Radio value={3}>已拒绝</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="频道：" name="channel_id">
            {/* <Select style={{ width: 288 }}>
              <Select.Option value={1}>Java</Select.Option>
              <Select.Option value={2}>前端</Select.Option>  

              {channels.map((item) => (
                <Select.Option key={item.id} value={item.id}>
                  {' '}
                  {item.name}
                </Select.Option>
              ))}
            </Select> */}

            
<Channel width={288}/>
          </Form.Item>
          <Form.Item label="日期：" name="dateArr">
            {/* locale={locale} */}
            <DatePicker.RangePicker />
          </Form.Item>
          <Form.Item>
            <Button type="primary"  htmlType='submit'>筛选</Button>
          </Form.Item>
        </Form>
      </Card>

      <Card
        title={`根据筛选条件共查询到 100 条结果：`}
        style={{ marginTop: 24 }}
      >
        {/* 放置表格组件 */}
        <Table columns={columns} dataSource={results}   rowKey="id"
        pagination={{
          current:page,
          pageSize:per_page,
          total:total_count,
          onChange:onPageChange, 
          }}
        ></Table>
      </Card>
    </div>
  );
}
